package com.example.rabbitmq.work;

import com.example.rabbitmq.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        //创建连接
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.WORK_QUEUE, true, false, false, null);
        DefaultConsumer consumer = new DefaultConsumer(channel) {//重写handleDelivery方法
            //从队列中收到消息就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("收到消息：" + new String(body));
            }
        };
        channel.basicConsume(Constants.WORK_QUEUE, true, consumer);
        Thread.sleep(1000);
        //6.释放资源
        //可以只关闭connection，或channel在connection之前先关闭
//        channel.close();
//        connection.close();

    }
}
